<!--数据字典管理-->
<template>
  <div>
    <div style="height: 10px"></div>
    <div class="commonStyle nyContent">
      <div class="table-operator" v-if="(isStudent || isSuperAdmin) && hasPermission ('course:scheduling:saveSchedule')">
        <a-button type="primary" @click="selectCourse">选课</a-button>
      </div>
    <p slot="title">
      <a-tabs v-model="tabKey" :activeKey="tabKey" @change="changeTab">
        <a-tab-pane key="1" tab="课表展示"></a-tab-pane>
        <a-tab-pane key="2" tab="列表展示" force-render></a-tab-pane>
      </a-tabs>
    </p>

      <div v-if="tabKey === '1'" class="commonStyle nyContent" style="width: 1500px;height: 1500px">
        <FullCalendar ref="fullCalendar" :options="calendarOptions"></FullCalendar>
      </div>
      <a-table :columns="columns" :dataSource="scheduleList" :rowKey="record => record.recordId"
               :pagination="false">
        <span slot="index" slot-scope="text, record, index">
                    {{ index + 1 }}
                </span>
        <span slot="scheduleTime" slot-scope="text, record, index" :style="{color:(text === '1'?'#00ff00':'#000000')}">
                    {{ moment(record.date).format("YYYY-MM-DD") + ' ' + record.attendTime + '-' + record.finishTime }}
                </span>
        <span slot="operation" slot-scope="text, record, index" class="table-operation">
          <a @click="addOrUpdateLesson(record)"
             v-if=" hasPermission ('classT:save')">{{ record.courseObject === '1' && record.classId ? '编辑课堂' : '新增课堂' }}</a>
          <a @click="showMicroChangeSchedule(record)"
             v-if="(isTeacher || isSuperAdmin) &&  hasPermission ('course:scheduling:saveSchedule')">课程微调</a>
                </span>
      </a-table>
    </div>
    <add-edit ref="addEdit"
              :scheduleId="scheduleId"
              :objDTO="{}" @init="init"/>
    <add-schedule ref="addSchedule" @init="init"/>
    <micro-change-schedule ref="microChangeSchedule"  @init="init"/>
  </div>
</template>

<script>
import {mapState} from 'vuex'
import Util from '@/libs/util';
import FullCalendar from '@fullcalendar/vue'
import dayGridPlugin from '@fullcalendar/daygrid'
import listPlugin from '@fullcalendar/list'
import timeGridPlugin from '@fullcalendar/timegrid'
import interactionPlugin from '@fullcalendar/interaction'
import moment from 'moment'
import addEdit from "../lessonManage/addEdit.vue";
import addSchedule from "./addSchedule.vue";
import microChangeSchedule from "./microChangeSchedule.vue";

export default {
  name: 'scheduleTable',
  components: {
    addEdit,
    microChangeSchedule,
    addSchedule,
    FullCalendar
  },
  data() {
    return {
      title: true,
      courseCountObj: {},
      tabKey: '1',
      weekList: [],
      scheduleList: [],
      classroomData: [],
      courseData: [],
      teacherData: [],
      params: {},
      isSuperAdmin:sessionStorage.getItem('user') === 'superAdmin',
      isAdmin:sessionStorage.getItem('user') === 'admin',
      isStudent:sessionStorage.getItem('roleIds').indexOf('bf87a2d6702c3ee927f113806e7a9736') > 0,
      isTeacher:sessionStorage.getItem('roleIds').indexOf('c2eb3ed226c8d4f52d9203ead594817d') > 0,
      searchKey: '',
      scheduleId: '',
      courseObj: {},
      selectedNode: {id: '', name: ''},
      array: [10, 20, 30, 40],
      /*选中的记录*/
      selectedRowKeys: [],
      columns: [
        {title: '序号', key: 'index', width: '8%', align: 'center', scopedSlots: {customRender: 'index'}},
        {title: '课程名称', dataIndex: 'courseName', key: 'courseName', width: '10%'},
        {title: '上课实验室', dataIndex: 'classroomName', key: 'classroomName', width: '10%'},
        {title: '授课教师', dataIndex: 'teacherName', key: 'teacherName', width: '8%'},
        {title: '上课专业', dataIndex: 'majorName', key: 'majorName'},
        {
          title: '上课班级',
          dataIndex: 'className',
          key: 'className',
          width: '10%',
          scopedSlots: {customRender: 'stage'}
        },
        {
          title: '上课时间',
          dataIndex: 'scheduleTime',
          key: 'scheduleTime',
          width: '15%',
          scopedSlots: {customRender: 'scheduleTime'}
        },
        {title: '实际上课时间', key: 'realStartTime', dataIndex: 'realStartTime', width: '15%'},
        {title: '操作', key: 'operation', width: '15%', scopedSlots: {customRender: 'operation'}}
      ],
      calendarOptions: {
        plugins: [dayGridPlugin, listPlugin, timeGridPlugin, interactionPlugin],
        initialView: 'timeGridWeek',
        locale: 'zh',
        // 每周开始是周几，Sunday=0, Monday=1
        firstDay: '1',
        // 时间轴间距
        slotMinTime: '07:00',
        slotMaxTime: '18:00',
        slotDuration: '00:' + 30 + ':00',
        // 是否显示第几周
        weekNumbers: true,
        weekText: '周',
        // 是否显示当前时间标记
        nowIndicator: true,
        // 是否显示全天插槽
        allDaySlot: false,
        // 日期否可点击
        navLinks: true,
        // 月视图，是否为指定周数高度，true 6周高度
        fixedWeekCount: false,
        // 月视图，是否显示非本月日期
        showNonCurrentDates: false,
        // 月视图，限制每天显示最大事件数，不包括+more链接，false 全部显示，true 限制为日单元格的高度，number 限制为指定行数高度
        dayMaxEvents: true,
        // 与dayMaxEvents类似，区别为包括+more链接
        // dayMaxEventRows: true,
        // 是否可拖拽
        editable: this.handleEditable(),
        events: [],
        headerToolbar: {
          start: 'prev,next today',
          center: 'title',
          end: 'timeGridWeek,dayGridMonth'
        },
        buttonText: {
          today: '今天',
          month: '月',
          week: '周',
          day: '日',
          list: '周列表'
        },
        slotLabelFormat: {
          hour: 'numeric',
          minute: '2-digit',
          hour12: false
        },
        eventTimeFormat: {
          hour: 'numeric',
          minute: '2-digit',
          hour12: false
        },
        datesSet: this.datesSet,
        dayHeaderContent: this.dayHeaderContent,
        eventContent: this.eventContent,
        eventClick: this.handleEventClick,
        dateClick: this.handleDateClick,
        // 当事件拖动时触发
        eventDragStart: this.eventDragStart,
        // 当事件拖动停止时触发
        eventDragStop: this.eventDragStop,
        // 当拖动停止并且事件移动到不同的日子/时间时触发
        eventDrop: this.eventDrop,
        // 当外部可拖动元素或来自另一个日历的事件被拖放到该日历中时调用
        drop: this.drop,
        // 当带有关联事件数据的外部可拖动元素拖放到日历中时调用，或来自另一个日历的事件
        eventReceive: this.eventReceive,
        // 当一个日历上的事件即将拖放到另一个日历上时触发
        eventLeave: this.eventLeave,
        // 开始缩放时触发
        eventResizeStart: this.eventResizeStart,
        // 停止缩放时触发
        eventResizeStop: this.eventResizeStop,
        // 当缩放停止且事件持续时间发生更改时触发
        eventResize: this.eventResize
      }
    }
  },
  computed: {
    moment() {
      return moment
    },
    courseManagePageData() {
      return this.$store.state.courseManage.courseManagePageData
    },
    ...mapState({
      pageVal: state => state.courseManage.page,
    }),

  },
  filters: {
    filterWord(value, list) {
      for (let i = 0; i < list.length; i++) {
        if (value === list[i].value) {
          return list[i].label
        }
      }
    },
  },
  methods: {
    handleEditable(){
      return sessionStorage.getItem('roleIds').indexOf('c2eb3ed226c8d4f52d9203ead594817d') > 0 || sessionStorage.getItem('user') === 'superAdmin' || sessionStorage.getItem('user') === 'admin'
    },
    changeTab(activeKey) {
      this.tabKey = activeKey
    },
    emitEmpty() {
      this.searchKey = ''
      this.init()
    },
    reStore() {
      this.searchKey = ''
      this.init();
    },

    editDTO(Obj) {
      this.objDTO = {...Obj}
      this.title = false
      this.$refs.addEdit.showEdit(this.objDTO)
    },
    selectCourse() {
      this.$refs.addSchedule.showModal()
    },
    clearDTO() {
      this.objDTO = {
        id: '',
        name: '',
      }
    },
    /*
     * 过滤输入框输入的特殊字符
     * */
    formatEnterContent(value) {
      let a = Util.clearSpecialChart(value);
      this.searchKey = a
    },

    /**
     * Function    : init
     * Description : 初始化列表
     * Input       : none
     * Return      : none
     */
    init() {
      this.getScheduleList()
    },


    /**
     * Function    : delRole
     * Description : 批量删除角色
     * Input       : none
     * Return      : none
     */
    enableDTO(obj) {
      this.$confirm({
        title: '确认禁用【' + obj.name + '】吗？',
        okText: '确定',
        cancelText: '取消',
        onOk: () => {
          let _this = this
          this.$store.dispatch('enableCourseAct', {id: obj.id}).then(response => {
            if (response.code === 0) {
              _this.init()
              this.$message.success(response.message)
            } else {
              this.$message.error(response.message)
            }
          })
        },
      })
    },
    scheduleCourse(record) {
      this.courseObj = {...record}
      this.$refs.schedule.showModal()
    },
    /**
     * Function    : delRole
     * Description : 批量删除角色
     * Input       : none
     * Return      : none
     */
    disableDTO(obj) {
      this.$confirm({
        title: '确认禁用【' + obj.name + '】吗？',
        okText: '确定',
        cancelText: '取消',
        onOk: () => {
          let _this = this
          this.$store.dispatch('disableCourseAct', {id: obj.id}).then(response => {
            if (response.code === 0) {
              _this.init()
            } else {
              this.$message.error(response.message)
            }
          })
        },
      })
    },

    /**
     * Function    : handleSubmit
     * Description : 查询按钮
     * Input       : none
     * Return      : none
     */
    handleSubmit() {
      this.init()
    },
    getScheduleList() {
      let _this = this;
      if (this.tabKey === '1') {
        _this.params.startDate = moment(this.$refs.fullCalendar.getApi().view.currentStart).format('YYYY-MM-DD')
        _this.params.endDate = moment(this.$refs.fullCalendar.getApi().view.currentEnd).endOf('month').format('YYYY-MM-DD')
      }
      _this.params.courseObject = (this.isSuperAdmin || this.isTeacher || this.isAdmin)?'1':'2'
      _this.$store.dispatch('GetCourseSchedulingCourseCountAct', _this.params).then(response => {
        if (response.code === 0) {
          let data = response.data;
          this.courseCountObj = data
        } else {
          _this.$message.error(response.message)
        }
      })
      _this.$store.dispatch('getScheduleListAct', _this.params).then(response => {
        if (response.code === 0) {
          let data = response.data;
          this.scheduleList = data
          this.calendarOptions.events = []
          data.forEach(item => {
            let date = moment(item.date).format("YYYY-MM-DD")
            this.calendarOptions.events.push({
              id: item.id,
              title: item.courseName + ' ' + item.classroomName + ' ' + item.teacherName + ' ' + item.className,
              start: date + ' ' + item.attendTime,
              end: date + ' ' + item.finishTime,
              extendedProps: item,
              backgroundColor: item.backgroundColor
            })
          })
        } else {
          _this.$message.error(response.message)
        }
      })
    },

    datesSet(info) {
      this.getScheduleList()
    },
    eventContent(info) {
      let _this = this;
      let extendedProps = info.event.extendedProps
      return {
        html: `<div >
                    <span style="font-size: 15px">${info.timeText}</span><br/>
                    <span style="font-size: 15px">${extendedProps.courseName}</span><br/>
                    <span style="font-size: 15px">${extendedProps.classroomName}</span><br/>
                    <span style="font-size: 15px">${extendedProps.teacherName}</span><br/>
                    <span style="font-size: 15px">${extendedProps.className}</span><br/>
                    <div style="float: right">
                        <span >${(!_this.isStudent)?((extendedProps.courseObject === '1' && extendedProps.classTId) ? '点击编辑课堂' : '点击新增课堂'):''}</span>
                    </div>

                </div>`
      }
    },
    dayHeaderContent(info) {
      if (info.view.type === 'dayGridMonth') {
        return {html: `<div class="fc-scrollgrid-sync-inner"><a class="fc-col-header-cell-cushion">${info.text}</a></div>`}
      } else if (info.view.type === 'timeGridWeek') {
        return {
          html: `<div class="fc-scrollgrid-sync-inner">
                    <span class="fc-col-header-cell-cushion" onclick="null"
                        data-navlink="{&quot;date&quot;:&quot;${moment(info.date).format('YYYY-MM-DD')}&quot;,&quot;type&quot;:&quot;day&quot;}" tabindex="0">${info.text}</span>
                    <span id="tams-course-count-${moment(info.date).format('YYYY-MM-DD')}" style="cursor: default;">${this.getCourseCount(info.date)}</span>节课
                </div>`
        }
      } else if (info.view.type === 'timeGridDay') {
        return {
          html: `<div class="fc-scrollgrid-sync-inner">
                     <span class="fc-col-header-cell-cushion">${info.text}</span>
                     <span id="tams-course-count-${moment(info.date).format('YYYY-MM-DD')}" style="cursor: default;">${this.getCourseCount(info.date)}</span>节课
                 </div>`
        }
      } else if (info.view.type === 'listWeek') {
        return {
          html: `<span class="fc-list-day-text"
                      data-navlink="${info.navLinkData.replace(/"/g, '&quot;')}" tabindex="0">${info.text}</span>
                 <span class="fc-list-day-side-text"
                      data-navlink="${info.navLinkData.replace(/"/g, '&quot;')}" tabindex="0">${info.sideText}</span>`
        }
      } else if (info.view.type === 'dayGridDay') {
        return {
          html: `<div class="fc-scrollgrid-sync-inner">
                     <a class="fc-col-header-cell-cushion">${info.text}</a>
                     <span id="tams-course-count-${moment(info.date).format('YYYY-MM-DD')}" style="cursor: default;">${this.getCourseCount(info.date)}</span>节课
                 </div>`
        }
      }
      return 'unknown view type'
    },
    getCourseCount(date) {
      const count = this.courseCountObj[moment(date).format('YYYY-MM-DD')]
      return count || 0
    },
    handleEventClick(info) {
      if (!this.isStudent) {
        this.scheduleId = info.event.id
        if (this.scheduleId) {
          let extendedProps = info.event.extendedProps;
          this.$refs.addEdit.showModal({
            scheduleId: this.scheduleId,
            classTId: extendedProps.classTId,
            realStartTime: extendedProps.realStartTime
          })
        }
      }
    },
    addOrUpdateLesson(record) {
      this.$refs.addEdit.showModal({
        scheduleId: record.id,
        classTId: record.classTId,
        realStartTime: record.realStartTime
      })
    },
    showMicroChangeSchedule(record) {
      this.$refs.microChangeSchedule.showModal(record.id,record.date,record.attendTime,record.finishTime)
    },
    handleDateClick(info) {
    },
    eventDragStart(info) {
    },
    eventDragStop(info) {

    },
    eventDrop(info) {
      let param = {
        id: info.event.id,
        date: moment(info.event.start).format('YYYY-MM-DD'),
        attendTime: moment(info.event.start).format('HH:mm'),
        finishTime: moment(info.event.end).format('HH:mm')
      }
      this.$store.dispatch('updateScheduleTimeAct', param).then(response => {
        if (response.code === 0) {
          this.init()
          this.$message.success(response.message)
        } else if (response.code === 100001) {
          let msgArray = JSON.parse(response.message)
          let msg = "";
          for (let index in msgArray) {
            msg = msg + '\n' + msgArray[index]
          }
          alert(msg)
        } else {
          this.$message.error(response.message)
        }
      })
    },
    drop(info) {
      console.log('drop', info)
    },
    eventReceive(info) {
      console.log('eventReceive', info)
    },
    eventLeave(info) {
      console.log('eventLeave', info)
    },
    eventResizeStart(info) {
      console.log('eventResizeStart', info)
    },
    eventResizeStop(info) {
      console.log('eventResizeStop', info)
    },
    eventResize(info) {
      console.log('eventResize', info)
      // this.UpdateCourseSchedulingTimeById({
      //   id: info.event.id,
      //   data: {
      //     date: moment(info.event.start).format('YYYY-MM-DD'),
      //     attendTime: moment(info.event.start).format('HH:mm:ss'),
      //     finishTime: moment(info.event.end).format('HH:mm:ss')
      //   }
      // }).then(res => {
      //   this.search()
      // }).catch(() => {
      //   this.search()
      // })
    }


  },
  created() {
    this.searchKey = this.$route.query.searchKey === undefined ? '' : this.$route.query.searchKey

  },


  mounted() {
    this.init()
  }
}
</script>
